import subprocess
import re
import pandas as pd
from read_xlsx_sheet1 import read_execle,Coating_Name,Coating_Name_row_element




def replace_text_in_file_sheet3_Commands_2(file_par, file_xlsx,start_tag, end_tag,a):
    sheet_name = f'Sheet{a}'  # 如果需要，指定工作表名称
    df = pd.read_excel(file_xlsx, sheet_name=sheet_name)

    # 查找包含"Sweep"的起始行
    start_row = df[df.iloc[:, 0].str.contains('Sweep', na=False)].index[0]

    # 从起始行开始，读取第一列的数据，直到遇到空单元格
    strings = []
    current_row = start_row + 1  # 从Sweep行的下一行开始
    while current_row < len(df):
        cell_value = df.iat[current_row, 0]  # 读取当前行第一列的值
        if pd.isna(cell_value):  # 如果单元格为空，则停止读取
            break
        strings.append(cell_value)  # 将非空单元格的值添加到列表中
        current_row += 1  # 移动到下一行


    print(strings)



    with open(file_par, 'r') as file:
        lines = file.readlines()

    # 标志变量，用于确定是否在Sweep和CalcEmission之间
    in_sweep_block = False

    # 存储匹配的行
    matched_lines1 = []
    matched_lines2 = []

    # 遍历文件中的每一行
    for line in lines:
        # 检查是否到达Sweep块的开始
        if line.strip() == end_tag:
            in_sweep_block = True
        # 检查是否到达Sweep块的结束
        elif start_tag in line:
            in_sweep_block = False
        # 如果在Sweep和CalcEmission之间，进行匹配检查
        elif in_sweep_block:
            for string in strings:
                # 使用正则表达式进行模糊匹配
                if re.search(re.escape(string), line, re.IGNORECASE):
                    # 如果行中包含"Disabled"，则删除它
                    # if 'Disabled' in line:
                    #     line = line.replace('Disabled ', '')
                    matched_lines1.append(line)
                    break  # 找到匹配项后，跳出当前循环，继续检查下一行

    # 打印匹配的行
    for line in matched_lines1:
        print(line, end='')


    # 遍历文件中的每一行
    for line in lines:
        # 检查是否到达Sweep块的开始
        if line.strip() == end_tag:
            in_sweep_block = True
        # 检查是否到达Sweep块的结束
        elif start_tag in line:
            in_sweep_block = False
        # 如果在Sweep和CalcEmission之间，进行匹配检查
        elif in_sweep_block:
            for string in strings:
                # 使用正则表达式进行模糊匹配
                if re.search(re.escape(string), line, re.IGNORECASE):
                    # 如果行中包含"Disabled"，则删除它
                    if 'Disabled' in line:
                        line = line.replace('Disabled ', '')
                    matched_lines2.append(line)
                    break  # 找到匹配项后，跳出当前循环，继续检查下一行

    # 打印匹配的行
    for line in matched_lines2:
        print(line, end='')


    last_generated_file = None

    for item_old, item_new in zip(matched_lines1, matched_lines2):
        StartPar = open(file_par, "r")
        StartPar_text = StartPar.read()
        
        # 如果是第一次循环，last_generated_file 为 None，使用原始文件名
        if last_generated_file is None:
            NewPar_filename = file_par
        else:
            # 否则，使用上一次生成的文件名
            NewPar_filename = last_generated_file
        
        NewPar = open(NewPar_filename, "w")
        
        # 替换指定的行
        Old_lines = item_old
        New_lines = item_new
        NewPar_text = StartPar_text.replace(Old_lines, New_lines)
        
        # 写入并关闭新文件
        NewPar.write(NewPar_text)
        NewPar.close()
        StartPar.close()
        
        # 更新 last_generated_file 为当前生成的文件名
        last_generated_file = NewPar_filename




def replace_text_in_file_sheet3_Commands(file_par, file_xlsx,start_tag, end_tag,a):
    sheet_name = f'Sheet{a}'  # 如果需要，指定工作表名称
    df = pd.read_excel(file_xlsx, sheet_name=sheet_name,engine='openpyxl')
    #打印表格内容
    two_row=0
    search_value = 'Sweep'
    found = False
    for index, row in df.iterrows():
        for col_index, cell_value in enumerate(row):
            # 检查单元格是否为字符串并且是否包含搜索值
            if isinstance(cell_value, str) and search_value == cell_value:
                # print(f"找到 '{search_value}' 在行索引 {index}，列索引 {col_index}")
                two_row=index
                found = True
                break  # 找到后可以退出内层循环
        if found:
            break
    if not found:
        print(f"在DataFrame中没有找到 '{search_value}'")



    list1=[]
    for row in df.iloc[two_row:].values:
        # 使用列表推导式来确保每个元素都被转换为字符串，同时跳过NaN值
        cleaned_row = ['{}'.format(item) if not pd.isna(item) else '' for item in row]
        combind_stirng=' '.join(cleaned_row).strip()
        print(combind_stirng)

        if combind_stirng=='Sweep':
            # print(combind_stirng)
            list1.append(combind_stirng)
        else:
            combind_result='Parameter '+combind_stirng
            # print(combind_result)
            list1.append(combind_result)
        # list1.append(' '.join(cleaned_row).strip())
    print(list1)
    len_list1=len(list1)

    with open(file_par, 'r') as file:
        lines = file.readlines()
    start_extract = False
    modified_lines = []

    # 倒序遍历文件内容
    for i in range(len(lines) - 1, -1, -1):
        line = lines[i]
        if end_tag in line:  # 如果找到 end_tag（Sweep），停止查找
            break
        if start_tag in line:  # 如果找到 start_tag（CalcEmission），开始替换
            start_extract = True
            modified_lines.insert(0, line)
            # 添加新内容，每个元素占据一行
            # for content in file_par:
            #     print(content)
            #     modified_lines.insert(0, content + '\n')
            continue
        if start_extract:
            if 'Disabled' in line:
                # 包含 'Disabled' 的行保持不变
                modified_lines.insert(0, line)
            continue
        else:
            modified_lines.insert(0, line)
    # print(modified_lines)

    # 将未处理的行添加到结果中
    for i in range(len(lines) - 1, -1, -1):
        if lines[i] not in modified_lines:
            # print(lines[i])
            modified_lines.insert(0, lines[i])


    with open(file_par, 'w') as file:
        file.writelines(modified_lines)


#################################################################

    with open(file_par, 'r') as file:
        lines = file.readlines()

    start_extract = False
    modified_lines = []
    #模糊查询end_tag
    end_tag_pattern = re.compile(end_tag)

    for line in lines:
        if start_tag in line:  # 如果找到 start_tag，包括这一行
            modified_lines.append(line)
            start_extract = True
            # 添加新内容，每个元素占据一行
            for content in list1:
                modified_lines.append(content + '\n')
            continue
        elif start_extract:
            if end_tag_pattern.search(line):  # 如果找到 end_tag，跳过这一行
                modified_lines.append(line)
                start_extract = False
                continue  # 跳过 end_tag 所在的行
            else:
                # 跳过旧内容，因为我们已经用新内容替换了
                continue
        else:
            modified_lines.append(line)  # 复制旧内容

    with open(file_par, 'w') as file:
        file.writelines(modified_lines)


# 调用函数
# file_par = 'emitter.txt'  # 替换为你的文件路径
# file_xlsx ='C:\\Users\\admin\\Desktop\\主动光学仿真\\仿真设置.xlsx'
# start_tag = 'Commands'
# end_tag = 'CalcEmission'

# replace_text_in_file_sheet3_Commands(file_par, file_xlsx,start_tag, end_tag,3)
